package com.atguigu.admin.controller;

import com.atguigu.admin.bean.Account;
import com.atguigu.admin.bean.User;
import com.atguigu.admin.service.impl.AccountService;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.annotations.Mapper;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpSession;


@Slf4j
@Controller
@MapperScan(value = "com.atguigu.admin.mapper")
public class IndexController {


    @Autowired
    JdbcTemplate jdbcTemplate;

    @Autowired
    AccountService accountService;

    /**
     * 来登录页
     *
     * @return
     */

    @ResponseBody
    @GetMapping("/acct")
    public Account getAccountById(@RequestParam("id") Long id){
        return accountService.getAcctById(id);
    }

    @GetMapping("/sql")
    @ResponseBody
    public String queryForDb(){

        Integer integer = jdbcTemplate.queryForObject("select count(*) from student", Integer.class);
        log.info("总记录数:"+integer);
        log.info("数据源类型："+jdbcTemplate.getDataSource().getClass());
        return integer.toString();
    }

    @GetMapping(value = {"/", "/login"})
    public String loginPage() {

        return "login";
    }


    @PostMapping("/login")
    public String main(User user, HttpSession session, Model model) { //RedirectAttributes

        if (StringUtils.hasLength(user.getUserName()) && "123456".equals(user.getPassword())) {
            //把登陆成功的用户保存起来
            session.setAttribute("loginUser", user);
            //登录成功重定向到main.html;  重定向防止表单重复提交
            return "redirect:/main.html";
        } else {
            model.addAttribute("msg", "账号密码错误");
            //回到登录页面
            return "login";
        }

    }

    /**
     * 去main页面
     *
     * @return
     */
    @GetMapping("/main.html")
    public String mainPage(HttpSession session, Model model) {
        log.info("当前方法是：{}","main.Page");
        return "main";
    }
}
